<template>
  <div class="reservation-management">
    <a-card title="预约管理" class="management-card">
      <!-- 统计信息 -->
      <div class="stats-section">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-statistic title="今日预约" :value="todayCount" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="待确认" :value="pendingCount" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="已确认" :value="confirmedCount" />
          </a-col>
          <a-col :span="6">
            <a-statistic title="总预约" :value="totalCount" />
          </a-col>
        </a-row>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-select
              v-model:value="filters.status"
              placeholder="选择状态"
              @change="loadReservations"
              style="width: 100%"
            >
              <a-select-option value="">全部状态</a-select-option>
              <a-select-option value="pending">待确认</a-select-option>
              <a-select-option value="confirmed">已确认</a-select-option>
              <a-select-option value="cancelled">已取消</a-select-option>
              <a-select-option value="completed">已完成</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-select
              v-model:value="filters.type"
              placeholder="预约类型"
              @change="loadReservations"
              style="width: 100%"
            >
              <a-select-option value="">全部类型</a-select-option>
              <a-select-option value="1">场馆预约</a-select-option>
              <a-select-option value="2">场地预约</a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-date-picker
              v-model:value="filters.date"
              placeholder="选择日期"
              @change="loadReservations"
              style="width: 100%"
            />
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="loadReservations" :loading="loading">
              刷新
            </a-button>
          </a-col>
        </a-row>
      </div>

      <!-- 预约列表 -->
      <a-table
        :columns="columns"
        :data-source="reservations"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="reservationId"
        class="reservation-table"
      >
        <!-- 预约类型 -->
        <template #reservationType="{ record }">
          <a-tag :color="record.reservationType === 1 ? 'blue' : 'green'">
            {{ record.reservationType === 1 ? '场馆预约' : '场地预约' }}
          </a-tag>
        </template>

        <!-- 预约状态 -->
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>

        <!-- 预约详情 -->
        <template #details="{ record }">
          <div class="reservation-details">
            <div><strong>日期:</strong> {{ record.reservationDate }}</div>
            <div><strong>时段:</strong> {{ record.timeSlot }}</div>
            <div v-if="record.areaType"><strong>区域:</strong> {{ record.areaType }}</div>
            <div v-if="record.description" class="description">
              <strong>说明:</strong> {{ record.description }}
            </div>
          </div>
        </template>

        <!-- 操作 -->
        <template #action="{ record }">
          <a-space>
            <a-button
              v-if="record.status === 'pending'"
              type="primary"
              size="small"
              @click="updateStatus(record.reservationId, 'confirmed')"
            >
              确认
            </a-button>
            <a-button
              v-if="record.status === 'confirmed'"
              type="default"
              size="small"
              @click="updateStatus(record.reservationId, 'completed')"
            >
              完成
            </a-button>
            <a-button
              v-if="['pending', 'confirmed'].includes(record.status)"
              danger
              size="small"
              @click="updateStatus(record.reservationId, 'cancelled')"
            >
              取消
            </a-button>
            <a-button
              type="link"
              size="small"
              @click="viewDetails(record)"
            >
              详情
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 详情弹窗 -->
    <a-modal
      v-model:open="detailVisible"
      title="预约详情"
      :footer="null"
      width="600px"
    >
      <div v-if="selectedReservation" class="detail-content">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="预约类型">
            <a-tag :color="selectedReservation.reservationType === 1 ? 'blue' : 'green'">
              {{ selectedReservation.reservationType === 1 ? '场馆预约' : '场地预约' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="预约状态">
            <a-tag :color="getStatusColor(selectedReservation.status)">
              {{ getStatusText(selectedReservation.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="预约人">
            {{ selectedReservation.username }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ selectedReservation.phone || '未提供' }}
          </a-descriptions-item>
          <a-descriptions-item label="预约日期">
            {{ selectedReservation.reservationDate }}
          </a-descriptions-item>
          <a-descriptions-item label="预约时段">
            {{ selectedReservation.timeSlot }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedReservation.areaType" label="预约区域">
            {{ selectedReservation.areaType }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDateTime(selectedReservation.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedReservation.description" label="使用说明" :span="2">
            {{ selectedReservation.description }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import http from '@/utils/http'
import dayjs from 'dayjs'

// 响应式数据
const reservations = ref([])
const loading = ref(false)
const detailVisible = ref(false)
const selectedReservation = ref(null)

const filters = reactive({
  status: '',
  type: '',
  date: null
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
})

// 计算属性
const todayCount = computed(() => {
  const today = dayjs().format('YYYY-MM-DD')
  return reservations.value.filter(r => r.reservationDate === today).length
})

const pendingCount = computed(() => {
  return reservations.value.filter(r => r.status === 'pending').length
})

const confirmedCount = computed(() => {
  return reservations.value.filter(r => r.status === 'confirmed').length
})

const totalCount = computed(() => {
  return reservations.value.length
})

// 表格列定义
const columns = [
  {
    title: '预约人',
    dataIndex: 'username',
    key: 'username',
    width: 100
  },
  {
    title: '预约类型',
    key: 'reservationType',
    slots: { customRender: 'reservationType' },
    width: 100
  },
  {
    title: '预约详情',
    key: 'details',
    slots: { customRender: 'details' },
    width: 200
  },
  {
    title: '状态',
    key: 'status',
    slots: { customRender: 'status' },
    width: 80
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    customRender: ({ text }) => formatDateTime(text),
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    slots: { customRender: 'action' },
    width: 200
  }
]

// 方法
const loadReservations = async () => {
  loading.value = true
  try {
    // 获取当前用户的场馆ID
    const userInfo = getCurrentUser()
    if (!userInfo || !userInfo.userId) {
      message.error('请先登录')
      return
    }

    // 获取用户管理的场馆信息
    const gymResponse = await http.get(`/v1/gym/owner/${userInfo.userId}`)
    if (gymResponse.data.code !== 2000 || !gymResponse.data.data) {
      message.error('您还没有管理的场馆')
      return
    }

    const gymId = gymResponse.data.data.gymId
    
    // 获取场馆的预约记录
    const response = await http.get(`/v1/reservation/gym/${gymId}`)
    
    if (response.data.code === 2000) {
      let data = response.data.data || []
      
      // 应用筛选条件
      if (filters.status) {
        data = data.filter(item => item.status === filters.status)
      }
      if (filters.type) {
        data = data.filter(item => item.reservationType === parseInt(filters.type))
      }
      if (filters.date) {
        const filterDate = dayjs(filters.date).format('YYYY-MM-DD')
        data = data.filter(item => item.reservationDate === filterDate)
      }
      
      reservations.value = data
      pagination.total = data.length
    }
  } catch (error) {
    console.error('加载预约记录失败:', error)
    message.error('加载预约记录失败')
  } finally {
    loading.value = false
  }
}

const updateStatus = async (reservationId, status) => {
  try {
    const response = await http.put(`/v1/reservation/${reservationId}/status`, null, {
      params: { status }
    })
    
    if (response.data.code === 2000) {
      message.success('状态更新成功')
      loadReservations()
    } else {
      message.error(response.data.msg || '状态更新失败')
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    message.error('更新状态失败')
  }
}

const viewDetails = (record) => {
  selectedReservation.value = record
  detailVisible.value = true
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
}

const getStatusColor = (status) => {
  const colorMap = {
    pending: 'orange',
    confirmed: 'green',
    cancelled: 'red',
    completed: 'blue'
  }
  return colorMap[status] || 'default'
}

const getStatusText = (status) => {
  const textMap = {
    pending: '待确认',
    confirmed: '已确认',
    cancelled: '已取消',
    completed: '已完成'
  }
  return textMap[status] || status
}

const formatDateTime = (dateTime) => {
  return dateTime ? dayjs(dateTime).format('YYYY-MM-DD HH:mm') : ''
}

const getCurrentUser = () => {
  try {
    return JSON.parse(localStorage.getItem('user') || '{}')
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return {}
  }
}

// 生命周期
onMounted(() => {
  loadReservations()
})
</script>

<style scoped>
.reservation-management {
  padding: 20px;
}

.management-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.reservation-table {
  margin-top: 20px;
}

.reservation-details {
  font-size: 12px;
  line-height: 1.6;
}

.reservation-details .description {
  max-width: 150px;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.detail-content {
  padding: 16px 0;
}

@media (max-width: 768px) {
  .reservation-management {
    padding: 10px;
  }
  
  .stats-section,
  .filter-section {
    padding: 12px;
  }
}
</style>
